package pri.hillchen.springbootstd.sso.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pri.hillchen.springbootstd.sso.entity.SystemInfo;
import pri.hillchen.springbootstd.sso.entity.User;
import pri.hillchen.springbootstd.sso.service.SystemService;
import pri.hillchen.springbootstd.sso.service.UserService;
import pri.hillchen.springbootstd.sso.util.SpringMvcRequestUtil;
import pri.hillchen.springbootstd.sso.vo.SsoFailResult;
import pri.hillchen.springbootstd.sso.vo.SsoResult;
import pri.hillchen.springbootstd.sso.vo.SsoSuccessResult;
import pri.hillchen.springbootstd.sso.vo.SsoUser;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 9:23 2017/12/13 0013.
 */
@Controller
public class SsoLoginController {
    @Autowired
    private SystemService systemService;
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/axiosTest")
    @ResponseBody
    public String axiosTest(){
        return "hello,axios test!";
    }

    @RequestMapping("/ssoLogin")
    @ResponseBody
    public SsoResult ssoLogin(String userName, String password, String redirectUrl){
        User user = userService.findUser(userName);
        if( user.getPassword().equals(password)){
            SsoSuccessResult ssoSuccessResult = new SsoSuccessResult();
            ssoSuccessResult.setRedirectUrl(redirectUrl);
            ssoSuccessResult.setSsoUser(new SsoUser(userName));
            String token = userName+":"+password;
            ssoSuccessResult.setToken(userName+":"+password);
            stringRedisTemplate.opsForValue().set("token:"+token,token);
            return ssoSuccessResult;
        }else{
            return new SsoFailResult("登录用户名或密码不正确！");
        }
    }

    @RequestMapping("/getHello")
    @ResponseBody
    public String getHello(){
        String token = SpringMvcRequestUtil.getCurrentToken();
        String systemCode = SpringMvcRequestUtil.getCurrentRequestSys();
        SystemInfo systemInfo = systemService.getSystemInfo(systemCode);
        if(StringUtils.hasText(token) && token.equals(stringRedisTemplate.opsForValue().get("token:"+token))){
            return systemInfo.getSystemName()+"say : hello ";
        }else{
            return systemInfo.getLoginUrl();
        }
    }
}
